package com.hong.pdf2img.utils;

import com.hong.pdf2img.entity.SplitterDTO;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.multipdf.PDFMergerUtility;
import org.apache.pdfbox.multipdf.Splitter;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class PdfUtils {
    /**
     * 读取pdf中文字信息(全部)
     */
    public static void READPDF(String inputFile){
        //创建文档对象
        PDDocument doc =null;
        String content="";
        try {
            //加载一个pdf对象
            doc =Loader.loadPDF(new File(inputFile));
            //获取一个PDFTextStripper文本剥离对象
            PDFTextStripper textStripper =new PDFTextStripper();
            textStripper.setSortByPosition(true);
            content=textStripper.getText(doc);
//            vo.setContent(content);
            System.out.println("内容:"+content);
            System.out.println("全部页数"+doc.getNumberOfPages());
            //关闭文档
            doc.close();
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
    /**
     * 合并PDF
     * @param inputStreams 需合并的pdf文件流
     * @param bothPath 合并后的pdf文件路径
     * @param destinationFileName 合并后的pdf文件名
     */
    public static void MergePdf(List<InputStream> inputStreams, String bothPath, String destinationFileName) throws Exception {
        // org.apache.pdfbox.util.PDFMergerUtility：pdf合并工具类
        PDFMergerUtility mergePdf = new PDFMergerUtility();
        File file = new File(bothPath);
        if (!file.exists()) {
            file.mkdirs();
        }
//        mergePdf.addSources(inputStreams);
        // 设置合并生成pdf文件名称
        mergePdf.setDestinationFileName(bothPath + File.separator + destinationFileName);
        // 合并PDF
//        mergePdf.mergeDocuments();
        for (InputStream in : inputStreams) {
            if (in != null) {
                in.close();
            }
        }
    }
    /**
     * 读取pdf中文字信息(指定从第几页开始)
     */
//    public static pdfDomainVO readPageNO(pdfDomainVO vo){
//        String content="";
//        try{
//            PDDocument document = PDDocument.load(vo.getInputfile());
//            // 获取页码
//            int pages = document.getNumberOfPages();
//            // 读文本内容
//            PDFTextStripper stripper=new PDFTextStripper();
//            // 设置按顺序输出
//            stripper.setSortByPosition(true);
//            stripper.setStartPage(vo.getPageno());
//            stripper.setEndPage(vo.getPageno());
//            //获取内容
//            content = stripper.getText(document);
//            vo.setContent(content);
//            System.out.println("function : readPageNO over");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return vo;
//    }

    /**
     * 拆分pdf
     * @param sourcePdf 源pdf（路径+文件名+文件后缀）
     * @param splitPath 拆分后的文件路径
     * @param splitFileName 拆分后的文件名（不含后缀）
     * @param splitterDTOS 拆分规则
     * @return finalPdfs 最终拆分成的pdf
     */
    private List<String> spitPdf(String sourcePdf, String splitPath, String splitFileName, List<SplitterDTO> splitterDTOS) throws IOException {
        List<String> finalPdfs = new ArrayList<>();
        int j = 1;
        String splitPdf = splitPath + "\\" + splitFileName + "_";

        for (SplitterDTO splitterDTO : splitterDTOS) {
            // Loading an existing PDF document
            File file = new File(sourcePdf);
            PDDocument document = Loader.loadPDF(file);
            // Instantiating Splitter class
            Splitter splitter = new Splitter();
            splitter.setStartPage(splitterDTO.getStartPage());
            splitter.setSplitAtPage(splitterDTO.getSplitAtPage());
            splitter.setEndPage(splitterDTO.getEndPage());
            // splitting the pages of a PDF document
            List<PDDocument> Pages = splitter.split(document);
            // Creating an iterator
            Iterator<PDDocument> iterator = Pages.listIterator();
            // Saving each page as an individual document
            while(iterator.hasNext()) {
                PDDocument pd = iterator.next();
                String pdfName = splitPdf+ j++ +".pdf";
                pd.save(pdfName);
                finalPdfs.add(pdfName);
            }
            document.close();
        }

        return finalPdfs;
    }
}
